package xiaoa.java.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import xiaoa.java.utils.time.DateFormatUtils;

/**
 * server服务
 * @author xiaoa
 * @date 2017年8月10日 下午11:36:30
 * @version V1.0
 *
 */
public class ServerHander {
	
	/**
	 * 处理服务
	 * @Title: doHandle
	 * @author xiaoa
	 */
	public static void doHandle(ServerSocket  server)throws Throwable{
		
		 try {
		    	
	         final int[]  count = new int[]{0};
		   	   
	    	while(true){
				
				final Socket  client =  server.accept();
				
				Runnable run = new Runnable() {
					
					
					@Override
					public void run() {
						
						int countTemp = count[0] = count[0] + 1;
						
						long statTime = System.currentTimeMillis();
						
						System.out.println(countTemp +  ":==  server ==client host = " + client.getInetAddress().getHostAddress() + "  port = " + client.getPort());
						try {
							
							OutputStream	out = client.getOutputStream();
							
							InputStream  input =  client.getInputStream();
							
							BufferedReader  reader = new BufferedReader(new InputStreamReader(input));
							
							String line = null;
							
							StringBuilder  response = new StringBuilder();

							int length = -1;

							StringBuilder  body = new StringBuilder();

							boolean isBody = false;

							
							while( body.length() != length && (line = reader.readLine()) != null ){

								if (!isBody && line.contains("content-length")){

									length = Integer.valueOf(line.split(":")[1].trim());

								}

								if (isBody){
									body.append(line).append("/n");
								}

								// 判断是否是分隔符
								if (line.equals("")){

									if (length == -1){
										length = 0;
									}

									isBody = true;

								}

								System.out.println("line = " + line);


							}

							System.out.println("body = " + body);


							System.out.println("数据接收完成");
							
							response.append("</br>你好~！");
							response.append("</br>time:" + DateFormatUtils.format_yyyyMMddhhssSSS(new Date()) );
							response.append("</br>====client host = " + client.getInetAddress().getHostAddress() + " </br> port = " + client.getPort());
							response.append("</br> count = ").append(count[0]);
							response.append("</br>break</br>");
							
							response.append("</br><script src='http://localhost:8111/'/></br>");

							
							out.write(createRespBody(response.toString()).getBytes());
							out.flush();	
							System.out.println("请求结束");

							
							
						} catch (Throwable e) {
							e.printStackTrace();
						}
						
						System.out.println(countTemp +  ":==  server ==client host = " + client.getInetAddress().getHostAddress() + "  port = " + client.getPort() + " use = " + (System.currentTimeMillis() - statTime));
						
					}
				};
				
				// 处理线程
			    Thread  thread = new Thread(run);
			    thread.start();
			    
			}
	    	
		} catch (Exception e) {
			e.printStackTrace();
		}
	    
	    System.out.println("结束");
	    server.close();
		
	}


	

	/**
	 * 创建返回
	 * @Title: createRespBody
	 * @param body
	 * @return
	 * @author xiaoa
	 */
	private static String createRespBody(String body){
		
		
		String resp =   "HTTP/1.1 200 OK" + "\n"
						+"Server: xiaoa" + "\n"
						+"X-Powered-By: PHP/5.3.29" + "\n"
						+"Set-Cookie: real_ipd=211.161.240.20; expires=Wed, 19-Jul-2017 23:54:42 GMT; path=/" + "\n"
						+"Set-Cookie: ECS_ID=3289a092ee02170b40ea7e6e1274b15aaf7943d6; expires=Wed, 26-Jul-2017 13:54:42 GMT; path=/" + "\n"
						+"Cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" + "\n"
						+"Set-Cookie: PHPSESSID=foeije618v9ibc9g80galpui83; path=/" + "\n"
						+"Expires: Thu, 19 Nov 1981 08:52:00 GMT" + "\n"
						+"Pragma: no-cache" + "\n"
						+"Set-Cookie: ECS[visit_times]=1; expires=Thu, 19-Jul-2018 05:54:42 GMT; path=/" + "\n"
						+"Vary: Accept-Encoding" + "\n"
						+"Connection: keep-alive" + "\n"
						+"Transfer-Encoding: chunked" + "\n"
						+"Content-Type: text/html; charset=utf-8"+ "\n"
						+ "\n"
						+ body.length() + "d" + "\n"
						
						+ body
		
		                + "\n"
						+ "\n"
		                + "0";
		
		return resp;
		           
		
		
	}
	

}
